﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ImpressionPrint.Model;
using ImpressionPrint.Utility;
using Qiniu.IO;
using Qiniu.RS;
using Senparc.Weixin.MP.AdvancedAPIs;
using WeChatJsSdk.SdkCore;

namespace ImpressionPrint.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            ViewBag.Message = "修改此模板以快速启动你的 ASP.NET MVC 应用程序。";

            return View();
        }

        public ActionResult OrderEnterPage()
        {
            return View();
        }

        public ActionResult OrderListPage()
        {
            //string appId = System.Configuration.ConfigurationManager.AppSettings["WeChatAppId"];
            //string appSecret = System.Configuration.ConfigurationManager.AppSettings["WeChatAppSecret"];
            //bool debug = System.Configuration.ConfigurationManager.AppSettings["WeChatAppSecret"].ToLower() == "true";

            //JSSDK sdk = new JSSDK(appId, appSecret, debug);
            //SignPackage config = sdk.GetSignPackage(JsApiEnum.chooseImage | JsApiEnum.uploadImage);
            //System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            //ViewBag.config = serializer.Serialize(config);

            var mobile = Request.QueryString["m"];
            if (!string.IsNullOrEmpty(mobile))
            {
                var orderList = HttpContext.Cache.Get(mobile);
                if (orderList != null && (orderList as InvokeResult<List<OrderDetail>>).data != null)
                {
                    ViewBag.order = JsonHelper.SerializeObject(orderList);
                    return View(orderList as InvokeResult<List<OrderDetail>>);
                }
                HttpHelper httpHelper = new HttpHelper();
                orderList = httpHelper.post<InvokeResult<List<OrderDetail>>>(weixinhost, "QueryUnUploadOrderInfoByMobile", mobile);
                if (orderList != null && (orderList as InvokeResult<List<OrderDetail>>).data != null && (orderList as InvokeResult<List<OrderDetail>>).data.Count > 0)
                {
                    HttpContext.Cache.Insert(mobile, orderList);
                    ViewBag.order = JsonHelper.SerializeObject(orderList);
                    return View(orderList);
                }
                else
                    return Redirect("./OrderEnterPage");
            }
            else
            {
                return Redirect("./OrderEnterPage");
            }
        }

        public ActionResult OrderList(string[] data)
        {
            var mobile = this.Request.QueryString["m"];
            var oid = this.Request.QueryString["oid"];
            var localidstr = HttpUtility.UrlDecode(Request.Form[0]) ?? "";
            var localids = localidstr.Split(new char[] { ',' });
            //var localids = JsonHelper.DeserializeObject<List<string>>(HttpUtility.UrlDecode(Request.Form[0]));

            var orderList = HttpContext.Cache.Get(mobile) as InvokeResult<List<OrderDetail>>;
            var orderDetails = orderList.data.Find((OrderDetail od) => od.no == oid);
            orderDetails.localIds = localids.ToList<string>();
            HttpContext.Cache.Insert(mobile, orderList);
            return Redirect("./OrderListPage?m=" + mobile);
        }

        public ActionResult PhotoListPage()
        {
            string appId = System.Configuration.ConfigurationManager.AppSettings["WeChatAppId"];
            string appSecret = System.Configuration.ConfigurationManager.AppSettings["WeChatAppSecret"];
            bool debug = System.Configuration.ConfigurationManager.AppSettings["WeChatJsDebug"].ToLower() == "true";

            JSSDK sdk = new JSSDK(appId, appSecret, debug);
            SignPackage config = sdk.GetSignPackage(JsApiEnum.chooseImage | JsApiEnum.uploadImage);
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            ViewBag.config = serializer.Serialize(config);

            var mobile = this.Request.QueryString["m"];
            var oid = this.Request.QueryString["oid"];
            if (!string.IsNullOrEmpty(mobile))
            {
                var orderList = (HttpContext.Cache.Get(mobile) ?? new InvokeResult<List<OrderDetail>>()) as InvokeResult<List<OrderDetail>>;
                if (orderList.data != null)
                {
                    var orderDetails = orderList.data.Find((OrderDetail od) => od.no == oid);
                    LogUtil.Info("初始化图片对象:" + JsonHelper.SerializeObject(orderDetails));
                    ////获取订单编号和订单数量
                    //OrderImageInfo orderImageInfo = new OrderImageInfo()
                    //{
                    //    oid = oid,
                    //    name = orderDetails.name,
                    //    localids = orderDetails.localIds,
                    //    uploadnum = orderDetails.uploadnum,
                    //    num = orderDetails.num
                    //};
                    //return View(orderImageInfo);
                    ViewBag.order = JsonHelper.SerializeObject(orderDetails);
                    return View(orderDetails);
                }
                else
                    return Redirect("./OrderEnterPage");
            }
            else
                return Redirect("./OrderEnterPage");
        }

        public ActionResult UploadImgToQiniu()
        {
            var serverid = this.Request.QueryString["s"];
            var oid = this.Request.QueryString["oid"];
            var mobile = this.Request.QueryString["m"];
            var tubW = Convert.ToInt32(this.Request.QueryString["w"].Split(new char[] { '.' })[0]);
            var wxFlag = string.IsNullOrEmpty(this.Request.QueryString["f"]) ? true : false;

            if (!string.IsNullOrEmpty(mobile))
            {
                var orderList = (HttpContext.Cache.Get(mobile) ?? new InvokeResult<List<OrderDetail>>()) as InvokeResult<List<OrderDetail>>;
                if (orderList.data != null)
                {
                    var orderDetails = orderList.data.Find((OrderDetail od) => od.no == oid);//根据订单ID获取订单明细信息
                    orderDetails.uploadnum++;
                    if (!string.IsNullOrEmpty(serverid))
                    {
                        HttpHelper httpHelper = new HttpHelper();
                        var photoSizeList = httpHelper.post<InvokeResult<List<PhotoSizeInfo>>>(apihost, "QueryPhotosize", "").data;
                        var photoSize = photoSizeList.Find((PhotoSizeInfo p) => p.name == orderDetails.size);
                        var sjradio = photoSize.width / photoSize.height;

                        if (wxFlag)
                        {
                            string appId = System.Configuration.ConfigurationManager.AppSettings["WeChatAppId"];
                            string appSecret = System.Configuration.ConfigurationManager.AppSettings["WeChatAppSecret"];

                            MemoryStream stream = new MemoryStream();
                            JSSDK jssdk = new JSSDK(appId, appSecret);
                            var accesstoken = jssdk.GetAccessToken();
                            MediaApi.Get(accesstoken, serverid, stream);

                            if (stream.Length > 10000)//小于10K的图片不予处理
                            {
                                OrderImage orderImg = new OrderImage();
                                orderImg.tubH = orderImg.tubW = tubW;
                                stream.Position = 0;
                                //计算图片的宽高
                                GetImageSize(stream, orderImg);

                                //计算照片是否旋转
                                var radio = orderImg.Width / orderImg.Height;
                                bool isRotateangle = false;
                                if (radio > sjradio)
                                    isRotateangle = true;

                                stream.Position = 0;
                                LogUtil.Info("授权token:" + accesstoken + "|微信ServerID:" + serverid + "|文件大小:" + stream.Length);
                                string filename = Guid.NewGuid().ToString().Replace("-", "") + ".jpg";
                                QiniuUploadResult uploadResult = new QiniuUploadTask(filename, stream, null, "").Run(null);
                                LogUtil.Info("七牛图片上传回执:" + JsonHelper.SerializeObject(uploadResult));
                                if (uploadResult.success)
                                {
                                    orderImg.serverid = serverid;
                                    if (isRotateangle)
                                        orderImg.rotateangle = 90;
                                    orderImg.num = 1;
                                    orderImg.url = uploadResult.url;
                                }
                                orderDetails.images.Add(orderImg);//添加当前图片信息
                                LogUtil.Info("图片对象:" + JsonHelper.SerializeObject(orderImg));
                                return Content(JsonHelper.SerializeObject(uploadResult));
                            }
                            else
                            {
                                LogUtil.Info("授权token:" + accesstoken + "|微信ServerID:" + serverid + "|文件大小:" + stream.Length);
                                LogUtil.Info("图片小于10KB,没有上传7牛服务器");
                                QiniuUploadResult uploadResult = new QiniuUploadResult()
                                {
                                    success = false
                                };
                                return Content(JsonHelper.SerializeObject(uploadResult));
                            }
                        }
                        else
                        {
                            var url = this.Request.QueryString["u"];

                            OrderImage orderImg = new OrderImage();
                            var imgInfo = JsonHelper.DeserializeObject<ImageInfo>(httpHelper.GetHtml(url + "?imageInfo"));
                            orderImg.Width = imgInfo.width;
                            orderImg.Height = imgInfo.height;
                            //计算照片是否旋转
                            var radio = (float)orderImg.Width / (float)orderImg.Height;
                            bool isRotateangle = false;
                            if (radio > sjradio)
                                isRotateangle = true;

                            orderImg.tubH = orderImg.tubW = tubW;
                            orderImg.serverid = serverid;
                            orderImg.num = 1;
                            orderImg.url = url;
                            if (isRotateangle)
                                orderImg.rotateangle = 90;
                            orderDetails.images.Add(orderImg);//添加当前图片信息
                            LogUtil.Info("图片对象:" + JsonHelper.SerializeObject(orderImg));
                            QiniuUploadResult uploadResult = new QiniuUploadResult()
                            {
                                url = url,
                                success = true
                            };
                            return Content(JsonHelper.SerializeObject(uploadResult));
                        }
                    }
                    else
                    {
                        QiniuUploadResult uploadResult = new QiniuUploadResult()
                        {
                            success = false
                        };
                        //return Content(JsonHelper.SerializeObject(uploadResult));
                        return Json(uploadResult, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    LogUtil.Info("订单对象丢失");
                    return Redirect("./OrderEnterPage");
                }
            }
            else
            {
                LogUtil.Info("手机号码为空");
                return Redirect("./OrderEnterPage");
            }
        }

        /// <summary>
        /// 图片裁剪
        /// </summary>
        /// <returns></returns>
        public ActionResult PhotoCutPage()
        {
            var serverid = this.Request.QueryString["s"];
            var oid = this.Request.QueryString["oid"];
            var mobile = this.Request.QueryString["m"];
            if (!string.IsNullOrEmpty(mobile))
            {
                var orderList = (HttpContext.Cache.Get(mobile) ?? new InvokeResult<List<OrderDetail>>()) as InvokeResult<List<OrderDetail>>;
                if (orderList.data != null)
                {
                    var orderDetails = orderList.data.Find((OrderDetail od) => od.no == oid);
                    ViewBag.order = JsonHelper.SerializeObject(orderDetails);
                    return View();
                }
                else
                {
                    return Redirect("./OrderEnterPage");
                }

            }
            else
                return Redirect("./OrderEnterPage");

            //var orderDetails = JsonHelper.DeserializeObject<OrderDetail>("{\"localIds\":[],\"packagetype\":\"\",\"no\":\"58d777946a024539967943a340c586a8\",\"name\":\"18寸以上大尺寸照片、艺术照、合照、婚纱..\",\"type\":\"普通照片\",\"paper\":\"柯达皇家\",\"size\":\"48寸\",\"num\":1,\"uploadnum\":0,\"source\":1,\"uploadtype\":1,\"imgurl\":\"http://wd.geilicdn.com/vshop338618746-1448254698183-4084561.jpg?w=110&h=110&cp=1\",\"aspectRatio\":\"0.75\",\"images\":[{\"tubW\":90,\"tubH\":90,\"serverid\":\"3pMFN4IXaZ8aghOQd4JnenKuihmCwd0DsKUpjDvsfD5ya8NXJYvxnkF_Xm04v2w-\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/062bffe918ce4f218ac6c5793ef89ee0.jpg\",\"Rotate\":\"0\",\"Width\":720,\"Height\":1280,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":2},{\"tubW\":90,\"tubH\":90,\"serverid\":\"anyRLjw_VtA6hEBAhipHxaQHhGJ_CwzJUcoGt6YjMgGWNd2bdj0xlUDo-M3QLOYL\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/98132f69188b4ec08d841515eb7de701.jpg\",\"Rotate\":\"0\",\"Width\":960,\"Height\":1280,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":3},{\"tubW\":90,\"tubH\":90,\"serverid\":\"LTagZwEbSLJaGX1Bo_n-TjBVI8fQGDyUjDLWo25VyEm1BS0afzS7V8Ir31ld1DA8\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/221040b1c76845e88035bb9ae943826e.jpg\",\"Rotate\":\"0\",\"Width\":960,\"Height\":1280,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":1},{\"tubW\":90,\"tubH\":90,\"serverid\":\"qc5vxX1IIZxB9o6i12uLB2tK3L_ZyxTntWeBqMcepyqXEr1aQaGr5TwMyVmzb877\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/4d90f5451f394d31a2e2e2e900364f03.jpg\",\"Rotate\":\"0\",\"Width\":720,\"Height\":1280,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":1},{\"tubW\":90,\"tubH\":90,\"serverid\":\"ACEnzJGqOFUTKdj2bJc3QubFLaLK16SME_hUAIXmf35XNgsFHNtq5l0jXdMV3l-R\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/3156b5daf79b4b8db287180546e61aad.jpg\",\"Rotate\":\"0\",\"Width\":640,\"Height\":512,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":1}]}");
            //var orderDetails = JsonHelper.DeserializeObject<OrderDetail>("{\"localIds\":[],\"packagetype\":\"\",\"no\":\"58d777946a024539967943a340c586a8\",\"name\":\"18寸以上大尺寸照片、艺术照、合照、婚纱..\",\"type\":\"普通照片\",\"paper\":\"柯达皇家\",\"size\":\"48寸\",\"num\":1,\"uploadnum\":0,\"source\":1,\"uploadtype\":1,\"imgurl\":\"http://wd.geilicdn.com/vshop338618746-1448254698183-4084561.jpg?w=110&h=110&cp=1\",\"aspectRatio\":\"0.75\",\"images\":[{\"tubW\":90,\"tubH\":90,\"serverid\":\"3pMFN4IXaZ8aghOQd4JnenKuihmCwd0DsKUpjDvsfD5ya8NXJYvxnkF_Xm04v2w-\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/062bffe918ce4f218ac6c5793ef89ee0.jpg\",\"rotateangle\":\"0\",\"Width\":720,\"Height\":1280,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":2},{\"tubW\":90,\"tubH\":90,\"serverid\":\"anyRLjw_VtA6hEBAhipHxaQHhGJ_CwzJUcoGt6YjMgGWNd2bdj0xlUDo-M3QLOYL\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/98132f69188b4ec08d841515eb7de701.jpg\",\"rotateangle\":\"0\",\"Width\":960,\"Height\":1280,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":3},{\"tubW\":90,\"tubH\":90,\"serverid\":\"LTagZwEbSLJaGX1Bo_n-TjBVI8fQGDyUjDLWo25VyEm1BS0afzS7V8Ir31ld1DA8\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/221040b1c76845e88035bb9ae943826e.jpg\",\"rotateangle\":\"0\",\"Width\":960,\"Height\":1280,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":1},{\"tubW\":90,\"tubH\":90,\"serverid\":\"qc5vxX1IIZxB9o6i12uLB2tK3L_ZyxTntWeBqMcepyqXEr1aQaGr5TwMyVmzb877\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/4d90f5451f394d31a2e2e2e900364f03.jpg\",\"rotateangle\":\"0\",\"Width\":720,\"Height\":1280,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":1},{\"tubW\":90,\"tubH\":90,\"serverid\":\"ACEnzJGqOFUTKdj2bJc3QubFLaLK16SME_hUAIXmf35XNgsFHNtq5l0jXdMV3l-R\",\"url\":\"http://7xj84r.com2.z0.glb.qiniucdn.com/3156b5daf79b4b8db287180546e61aad.jpg\",\"rotateangle\":\"0\",\"Width\":640,\"Height\":512,\"X\":0,\"Y\":0,\"CutW\":0,\"CutH\":0,\"num\":1}]}");
            //ViewBag.order = JsonHelper.SerializeObject(orderDetails);
            //return View();
        }

        /// <summary>
        /// 留白
        /// </summary>
        /// <returns></returns>
        public ActionResult LiuBai()
        {
            var oid = this.Request.QueryString["oid"];
            var mobile = this.Request.QueryString["m"];
            if (!string.IsNullOrEmpty(mobile))
            {
                var orderList = (HttpContext.Cache.Get(mobile) ?? new InvokeResult<List<OrderDetail>>()) as InvokeResult<List<OrderDetail>>;
                if (orderList.data != null)
                {
                    var orderDetails = orderList.data.Find((OrderDetail od) => od.no == oid);//根据订单ID获取订单明细信息
                    foreach (OrderImage oi in orderDetails.images)
                    {
                        oi.IsCut = false;//不自主裁剪
                        oi.sellerCut = false;//不卖家裁剪
                    }
                    return Redirect("./OrderListPage?m=" + mobile);
                }
                else
                {
                    LogUtil.Info("订单对象丢失");
                    return Redirect("./OrderEnterPage");
                }
            }
            else
            {
                LogUtil.Info("手机号码为空");
                return Redirect("./OrderEnterPage");
            }
        }

        /// <summary>
        /// 卖家裁剪
        /// </summary>
        /// <returns></returns>
        public ActionResult SellerCut()
        {
            var oid = this.Request.QueryString["oid"];
            var mobile = this.Request.QueryString["m"];
            if (!string.IsNullOrEmpty(mobile))
            {
                var orderList = (HttpContext.Cache.Get(mobile) ?? new InvokeResult<List<OrderDetail>>()) as InvokeResult<List<OrderDetail>>;
                if (orderList.data != null)
                {
                    var orderDetails = orderList.data.Find((OrderDetail od) => od.no == oid);//根据订单ID获取订单明细信息
                    foreach (OrderImage oi in orderDetails.images)
                    {
                        oi.IsCut = false;//不自主裁剪
                        oi.sellerCut = true;//卖家裁剪
                    }
                    return Redirect("./OrderListPage?m=" + mobile);
                }
                else
                {
                    LogUtil.Info("订单对象丢失");
                    return Redirect("./OrderEnterPage");
                }
            }
            else
            {
                LogUtil.Info("手机号码为空");
                return Redirect("./OrderEnterPage");
            }
        }

        /// <summary>
        /// 提交订单
        /// </summary>
        /// <returns></returns>
        public ActionResult SumbitOrder()
        {
            var oid = this.Request.QueryString["oid"];
            var mobile = this.Request.QueryString["m"];
            var postStr = HttpUtility.UrlDecode(Request.Form.ToString());
            var temp = JsonHelper.DeserializeObject<OrderDetail>(postStr);
            //LogUtil.Info("提交订单参数:" + postStr);
            if (!string.IsNullOrEmpty(mobile))
            {
                var orderList = (HttpContext.Cache.Get(mobile) ?? new InvokeResult<List<OrderDetail>>()) as InvokeResult<List<OrderDetail>>;
                //OrderDetail orderDetails = new OrderDetail();
                var index = 0;
                if (orderList.data != null)
                {
                    for (var i = 0; i < orderList.data.Count; i++)
                    {
                        if (orderList.data[i].no == oid)
                        {
                            //orderDetails = orderList.data[i];
                            index = i;
                        }
                    }
                    //var orderDetails = orderList.data.Find((OrderDetail od) => od.no == oid);//根据订单ID获取订单明细信息
                    //orderDetails = temp;
                    orderList.data[index] = temp;
                    //LogUtil.Info("orderDetails:" + JsonHelper.SerializeObject(orderDetails));
                    HttpContext.Cache.Insert(mobile, orderList);
                    //LogUtil.Info("orderList:" + JsonHelper.SerializeObject(orderList));
                    return Redirect("./OrderListPage?m=" + mobile);
                }
                else
                {
                    LogUtil.Info("订单对象丢失");
                    return Redirect("./OrderEnterPage");
                }
            }
            else
            {
                LogUtil.Info("手机号码为空");
                return Redirect("./OrderEnterPage");
            }
        }

        /// <summary>
        /// 提交所有订单
        /// </summary>
        /// <returns></returns>
        public ActionResult SumbitAllOrder()
        {
            var mobile = Request.QueryString["m"];
            if (!string.IsNullOrEmpty(mobile))
            {
                var orderList = HttpContext.Cache.Get(mobile);
                if (orderList != null)
                {
                    var objPara = orderList as InvokeResult<List<OrderDetail>>;
                    if (objPara.data != null)
                    {
                        HttpHelper httpHelper = new HttpHelper();
                        var result = httpHelper.post<InvokeResult>(weixinhost, "SumbitOrderInfo", objPara.data);
                        if (result.ok)
                        {
                            //清空缓存
                            HttpContext.Cache.Remove(mobile);
                        }
                        LogUtil.Info("提交订单回执数据" + JsonHelper.SerializeObject(result));
                        return Content(JsonHelper.SerializeObject(result));
                    }
                    return Redirect("./OrderEnterPage");
                }
                else
                    return Redirect("./OrderEnterPage");
            }
            else
            {
                return Redirect("./OrderEnterPage");
            }
            return Redirect("./OrderEnterPage");
        }

        /// <summary>
        /// 计算图片尺寸
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="orderImg"></param>
        private void GetImageSize(MemoryStream stream, OrderImage orderImg)
        {
            try
            {
                //计算图片尺寸
                System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                orderImg.Width = image.Width;
                orderImg.Height = image.Height;
            }
            catch
            {
                orderImg.Width = 0;
                orderImg.Height = 0;
            }
        }

        public ActionResult GetQiniuUpToken()
        {
            Qiniu.Conf.Config.ACCESS_KEY = "rN2Wx9usqx7K8EDQSkga1IQV1jNuP5uI0mYbFOEx";
            Qiniu.Conf.Config.SECRET_KEY = "mcuuFvsXSucmdhv7z2Fznwbi6iTpnKDvQhBKx7As";
            string spanceurl = "7xj84r.com2.z0.glb.qiniucdn.com";
            string bucketName = "muzhichun";
            PutPolicy policy = new PutPolicy(bucketName, 3600);
            string upToken = policy.Token();
            LogUtil.Info("七牛上传文件令牌:" + upToken);
            return Content("{\"uptoken\": \"" + upToken + "\"}");
        }

        public ActionResult About()
        {
            ViewBag.Message = "你的应用程序说明页。";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "你的联系方式页。";

            return View();
        }

        public ActionResult UploadTest()
        {
            return View();
        }
    }
}
